<template>
  <el-card>
    <el-form>
      <el-form-item label="角色名称">
        <el-input disabled v-model="roleName" />
      </el-form-item>
      <el-form-item>
        <el-tree
          :data="assignPermissionList"
          ref="treeRef"
          show-checkbox
          default-expand-all
          :props="{
            children: 'children',
            label: 'name',
          }"
          node-key="id"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="confirmAssignPermissionList"
          >保存</el-button
        >
        <el-button @click="goRoleAdministration">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "RoleAuth",
};
</script>

<script lang="ts" setup>
import { useRoute, useRouter } from "vue-router";
import { onMounted, ref } from "vue";
import {
  getPermissionListApi,
  getAssignPermissionApi,
} from "@/api/acl/permission";
import type { GetPermissionList } from "@/api/acl/model/permissionModel";
import { ElMessage } from "element-plus";
const route = useRoute();
const treeRef = ref();
const assignPermissionList = ref<GetPermissionList>([]);
const roleName = route.query.roleName as string;
const getRolePermissionList = async () => {
  const result = await getPermissionListApi(route.query.id as string);
  assignPermissionList.value = result.children;
  const selectAssignPermissionList = getSelectAssignPermissionList(
    result.children
  );
  treeRef.value.setCheckedKeys(selectAssignPermissionList);
};
onMounted(getRolePermissionList);
function getSelectAssignPermissionList(
  assignPermissionList: GetPermissionList
) {
  let selectAssignPermissionList: string[] = [];
  assignPermissionList.forEach((assignPermission) => {
    if (assignPermission.children && assignPermission.children.length) {
      const childrenAssignPermissionList = getSelectAssignPermissionList(
        assignPermission.children
      );
      selectAssignPermissionList = selectAssignPermissionList.concat(
        childrenAssignPermissionList
      );
      return;
    }
    // 如果没有子菜单
    if (assignPermission.select) {
      selectAssignPermissionList.push(assignPermission.id);
    }
  });
  return selectAssignPermissionList;
}
const router = useRouter();
const goRoleAdministration = () => {
  router.push({
    name: "Role",
  });
};
const confirmAssignPermissionList = async () => {
  await getAssignPermissionApi(route.query.id as string, [
    // 这里是发送选中的和半选的key
    ...treeRef.value.getCheckedKeys(),
    ...treeRef.value.getHalfCheckedKeys(),
  ]);
  goRoleAdministration();
  ElMessage.success("分配权限成功");
};
</script>

<style scoped></style>
